import React, { useCallback, useEffect, useState, useRef } from "react";
import { Form, Input, Button, Select, Col, Row, message } from "antd";
import request from "@/utils/request";
import MarkdownIt from "markdown-it";
import "../css/add.css";
import { withRouter } from "react-router";

const { Option } = Select;
const { TextArea } = Input;
const md = new MarkdownIt();
let refdiv;

function Put(props) {
    const [query, setQuery] = useState({}); // 搜索条件
    const [originData, setlist] = useState([]);
    const id = props.match.params.id;
    const [form] = Form.useForm()
    const [txt, changeTxt] = useState("");
    const [show, changeshow] = useState(false);
    const [initialValues, changevalue] = useState({})

    // 获取标签表单数据
  const getList = useCallback(async () => {
    const { data: res } = await request.get("/tag", { params: query });
    if (res.code !== 200) return message.error("获取数据失败！");
    setlist(res.data);
  }, []);
  useEffect(() => {
    getList();
  }, []);

  useEffect(function () {
    refdiv = React.createRef();
  }, []);

    useEffect(function () {
        request.get('/article/' + id).then(({ data: { data } }) => {
            // console.log(data[0]);
            // let content = data[0].content;
            // if (refdiv.current !== null) refdiv.current.innerHTML = content;
            data[0].content = data[0].content
                .replace(/<br\/>/g, "\r\n")
                // .replace(/\n/g, "<br/>")
                .replace(/&nbsp;/g, ' ');
            changevalue(() => {
                initialValues.title = data[0].title
                initialValues.descript = data[0].descript
                initialValues.keyworks = data[0].keyworks
                initialValues.tag = data[0].tag
                initialValues.content = data[0].content
                return initialValues
            })
            changeTxt(() => {
                return data[0].content
            })
            form.setFieldsValue(initialValues)
        })
        refdiv = React.createRef();
    }, []);

    const showTextArea = useCallback(function () {
        changeshow(function () {
            return !show;
        });
    });

    const onChange = useCallback(function Change(e) {
        changeTxt(function (txt) {
            let text = md.render(e.target.value);
            console.log(text);
            txt = text;
            console.log(refdiv);
            if (refdiv.current !== null) refdiv.current.innerHTML = txt;
            // console.log("refTxt", refdiv.current.innerHTML);
            return txt;
        });
    }, []);
    const onFinish = (values) => {
        console.log(values);
        request.put("/article/" + id, values).then(({ data }) => {
            console.log("data", data);
            if (data.code === 200) {
                message.success("数据修改成功");
            }
        });
    };

    // 点击存草稿按钮
    const Draft=useCallback(function(){
        message.success("还没这个功能哦，去试试别的叭")
    })

    return (
        <div>
            {/* form表单 字段 */}
            <Form
                form={form}
                labelCol={{ span: 3 }}
                // wrapperCol={{ span: 20 }}
                onFinish={onFinish}
            >
                <Row >
                    <Col span={10} style={{ paddingBottom: 10 }}>
                        <Form.Item
                            label="标题"
                            name="title"
                            rules={[{ required: true, message: "请输入标题" }]}

                        >

                            <Input placeholder="请输入标题" value={initialValues.title} />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item
                            label="描述"
                            name="descript"
                            initialValue={initialValues.descript}
                            rules={[{ required: true, message: "请输入描述" }]}
                        >
                            <Input placeholder="请输入简短的描述" />
                        </Form.Item>
                    </Col>
                </Row>
                <Row>
                    <Col span={10}>
                        <Form.Item
                            label="关键字"
                            name="keyworks"
                            initialValue={initialValues.keyworks}

                            rules={[{ required: true, message: "请输入关键字 " }]}
                        >
                            <Input
                                placeholder="请输入关键字"
                            // value={keyword}
                            />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item
                            label="标签"
                            name="tag"
                            initialValue={initialValues.tag}
                            rules={[{ required: true, message: "请选择标签!" }]}
                        >
                            <Select
                                mode="multiple"
                                allowClear
                                style={{ width: "100%" }}
                                placeholder="请选择标签"
                            >
                                {originData.map((item) => {
                                    return <Option key={item.lable}>{item.lable}</Option>;
                                })}
                            </Select>
                        </Form.Item>
                    </Col>
                </Row>

                {/* 文本框区域 */}
                <Row>
                    <Col span={11}>
                        <Form.Item
                            name="content"
                            rules={[{ required: true, message: "请输入内容!" }]}
                        >
                            <TextArea
                                className="focus"
                                showCount
                                maxLength={1000}
                                onChange={onChange}
                                autoSize={{ minRows: 18, maxRows: 30 }}
                                placeholder="请输入内容"
                                value={txt}
                            >
                            </TextArea>
                        </Form.Item>
                    </Col>

                    {/* 预览区域 */}
                    <Col span={11} style={show ? "" : { display: "none" }}>
                        <div
                            className="myshow"
                            style={{
                                border: "1px solid #ddd",
                                backgroundColor: "#fff",
                            }}
                            ref={refdiv}
                        ></div>
                    </Col>
                </Row>
                {/* 底部 */}

                <Button type="primary" style={{ width: "100px" }} htmlType="submit">
                    修改
                </Button>
                <Button
                    type="primary"
                    style={{ width: "100px", marginLeft: "20px" }}
                    onClick={showTextArea}
                >
                    {show ? "收起" : "预览"}
                </Button>
                <Button
                    type="primary"
                    danger
                    style={{ width: "100px", marginLeft: "20px" }} onClick={Draft}
                >
                    存草稿
                </Button>
            </Form>
        </div>
    );
}
Put = withRouter(Put)
export default Put;
